package com.mqb;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.util.matcher.AndRequestMatcher;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

/**
 * @author mqb
 * @date 2021/3/19 17:57
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Bean
    PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("spencer")
                .password("123")
                .roles("admin");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/js/**", "/css/**", "/images/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/anyone", "/login.html", "/login", "/ffu", "/fu").permitAll()  // 设置不需要登录就可以访问
                .and()
                .authorizeRequests()
                .anyRequest().authenticated();  // 设置所有请求都需要登录后才能访问

        http.formLogin()
                .loginPage("/login.html")       // 设置登录页
                .loginProcessingUrl("/login")   // 登录请求地址
                .defaultSuccessUrl("/success") // 登录成功后重定向到 /index
                .usernameParameter("name")
                .passwordParameter("passwd")
                .failureForwardUrl("/ffu")
                //.permitAll()                    // 这里不加permitAll的话要把登录页,登录请求配置到antMatchers中
                //.failureUrl("/fu")
                .and().csrf().disable();

        http.logout()
                .logoutUrl("/logout")
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout", "GET"))
                .logoutSuccessUrl("/out")
                .deleteCookies()
                .clearAuthentication(true)
                .invalidateHttpSession(true)
                .permitAll();
    }
}
